<template>
	<view class="content">
		<view v-for="(item, index) in collectList" :key="index">
			<view class="goods-item">
				<!-- 根据 isManaging 决定是否显示 radio -->
				<radio v-if="isManaging" :value="String(item.id)" :checked="item.selected"
					@click="toggleSelection(item)">
				</radio>
				<image class="goods-image" :src="item.commodityDto.pictureIntegrationDtoS[0].pictureUrl"
					mode="aspectFill"></image>
				<view class="goods-info"  @click="goDetail(item)">
					<p class="title">{{ item.commodityDto.commodityName }}</p>
					<p class="tags">
						{{ item.commoditySpecificationBasicInformationDto.attributeName }}:
						{{ item.commoditySpecificationBasicInformationDto.attributeValue }},
						<span v-if="item.commoditySpecificationAttributeInfoDto && 
									item.commoditySpecificationAttributeInfoDto.specificationName && 
									item.commoditySpecificationAttributeInfoDto.specificationValue">
							{{ item.commoditySpecificationAttributeInfoDto.specificationName }}:
							{{ item.commoditySpecificationAttributeInfoDto.specificationValue }}
						</span>
					</p>
					<p class="price">￥{{ item.commoditySpecificationAttributeInfoDto.sellingPrice }}</p>
				</view>
			</view>
		</view>
		<view class="bottomBox">
			<!-- 动态改变左按钮文字 -->
			<view class="leftButton" @click="handleLeftButtonClick">
				<radio v-if="isManaging" :checked="isAllSelected" @click.stop="toggleAllSelection"></radio>
				{{ isManaging ? (isAllSelected ? '取消全选' : '全选') : '清空'}}
			</view>
			<!-- 动态改变右按钮文字 -->
			<view class="rightButton" @click="checkout">
				{{ isManaging ? '取消收藏' : '管理' }}
			</view>
		</view>
		<view v-if="!collectList.length">
			<image style="margin:10%;" src='../../../static/null/null.png'></image>
		</view>

	</view>
</template>

<script>
	import {
		getUserInfo,
		getCollect,
		delAll,
		delCollectIds
	} from '@/api/user.js';

	export default {
		data() {
			return {
				isManaging: false, // 新增的状态变量
				isAllSelected: false, // 跟踪全选状态
				collectList: [],
				selectedItems: [], // 存储选中的商品
				userInfo: {},
				currentPage: 1, // 当前页码
				pageSize: 10, // 每页显示的商品数量
			}
		},
		mounted() {
			this.getUser();
			this.getCollectList();
			// 监听页面滚动事件
			uni.$on('reachBottom', this.loadMore);
		},
		beforeDestroy() {
			// 移除页面滚动事件监听
			uni.$off('reachBottom', this.loadMore);
		},
		methods: {
			// 获取用户信息
			getUser() {
				getUserInfo().then(res => {
					this.userInfo = res.data;
				});
			},
			getCollectList() {

				const params = {
					pageNumber: this.currentPage,
					pageSize: this.pageSize,
				};

				getCollect(params).then(res => {
					const newList = res.data.records.map(item => ({
						...item,
						selected: false // 确保每个项目都有selected属性
					}));

					if (this.currentPage === 1) {
						this.collectList = newList;
					} else {
						this.collectList = this.collectList.concat(newList);
					}

				}).catch(err => {
					console.error('获取收藏列表失败:', err);
				});
			},
			// 清空
			addDel() {
				const params = {
					userId: this.userInfo.id
				};
				delAll(params).then(res => {
					uni.showToast({
						icon: "none",
						title: '已清空'
					});
					this.getCollectList();
				});
			},
			toggleSelection(item) {
				item.selected = !item.selected;
				this.updateAllSelectedStatus();
			},
			checkout() {
				if (this.isManaging) {
					// 处于管理状态，获取选中的商品列表并取消收藏
					this.getSelectedItems();
					this.removeFavorites();
					// 退出管理状态
					this.isManaging = false;
					this.isAllSelected = false; // 取消全选状态
				} else {
					// 不处于管理状态，进入管理状态
					this.isManaging = true;
				}
			},
			getSelectedItems() {
				// 获取所有选中的商品
				this.selectedItems = this.collectList.filter(item => item.selected);
				console.log('Selected Items:', this.selectedItems);
			},
			// 根据 ids 删除收藏
			removeFavorites() {
				// 提取所有的 id 并确保唯一性（如果需要的话）
				const uniqueIds = new Set(this.selectedItems.map(item => item.id));
				// 将 Set 转换为逗号分隔的字符串，不添加大括号
				const idsString = Array.from(uniqueIds).join(',');
				// 打印结果，仅用于调试目的
				console.log(`{${idsString}}`); // 输出如 {1,2,3}，注意这只是打印，并不是实际传参
				// 调用删除收藏的接口
				delCollectIds(idsString).then(res => {
					uni.showToast({
						icon: "none",
						title: '清除成功'
					});
					this.getCollectList();
				}).catch(err => {
					console.error('Failed to delete favorites:', err);
				});
				// 更新收藏列表
			},
			handleLeftButtonClick(event) {
				if (!this.isManaging) {
					this.addDel();
				}
			},
			toggleAllSelection() {
				this.isAllSelected = !this.isAllSelected;
				this.collectList.forEach(item => {
					item.selected = this.isAllSelected;
				});
			},
			updateAllSelectedStatus() {
				// 检查是否所有商品都被选中
				this.isAllSelected = this.collectList.every(item => item.selected);
			},
			loadMore() {
				this.currentPage += 1;
				this.getCollectList();
			},
			goDetail(item){
				uni.navigateTo({
					url: '/pages/classification/goodsDetail/index?id=' + item.commodityId
				})
			}
		}
	}
</script>


<style lang="scss">
	@import '@/uni.scss'; // 导入全局 SCSS 变量文件

	.content {
		min-height: 100vh;
		background-color: #F3F3F3;
		position: relative;
	}

	.goods-item {
		display: flex;
		align-items: center;
		background-color: $uni-bg-color-white;
		padding: 20rpx 40rpx;
		margin: 2rpx 0rpx;
	}

	.goods-image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 20rpx;
	}

	.goods-info {
		flex: 1;
	}

	.title {
		height: 80rpx;
		font-size: $uni-font-size-base;
		color: $uni-text-color;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.tags {
		font-size: $uni-font-size-sm;
		color: $uni-text-color-grey;
		margin-top: 5rpx;
	}

	.price {
		font-size: 18px;
		color: #e4393c;
		margin-top: 5px;
	}

	.bottomBox {
		width: 100%;
		height: 100rpx;
		position: fixed;
		bottom: 0;
		z-index: 1000;
		background-color: $uni-color-fff;
		display: flex;

		.leftButton {
			width: 30%;
			text-align: center;
			line-height: 100rpx;
			color: $uni-text-color-grey;
		}

		.rightButton {
			width: 66%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: $uni-color-orange;
			color: white;
			border-radius: 80rpx;
			margin: 10rpx 0rpx;
		}
	}

	.loading-more,
	.no-more-data {
		text-align: center;
		padding: 20rpx;
		color: $uni-text-color-grey;
	}
</style>